<template>
	<view class="container">
		<uni-forms ref="form" :modelValue="formData" :rules="rules">
			<uni-forms-item>
				<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<image class="avatar" :src="formData.avatarUrl"></image>
				</button>
			</uni-forms-item>
			<uni-forms-item label="昵称" name="nickName">
				<uni-easyinput type="nickname" v-model="formData.nickName" @blur="inputnickName" placeholder="请输入昵称" />
			</uni-forms-item>
			<uni-forms-item label=" 手机号" name="phone">
				<uni-easyinput type="number" maxlength="11" :disabled="inputCode" v-model="formData.phone"
					placeholder="请输入手机号(选填)" />
				<view class="send-btn" hover-class="hover-send-btn" @click="requestCode"
					v-if="phone_len===11&&!inputCode&&formData.phone!=userinfo.phone">
					<text>验证码</text>
				</view>
				<view class="countdown-box" v-if="inputCode">
					<uni-countdown :show-day="false" :showHour="false" :showMin="false" :second="seconds" :fontSize="18"
						@timeup="timeup" color="#000" background-color="#f1f1f1" />
					<text>S</text>
				</view>
			</uni-forms-item>
			<uni-forms-item label=" 验证码" name="code" v-if="phone_len===11&&inputCode">
				<uni-easyinput type="number" maxlength="6" v-model="formData.code" placeholder="请输入短信验证码" />
			</uni-forms-item>
		</uni-forms>
		<view class="btn-submit">
			<button type="default" :disabled="submiting" @click="submit">提交</button>
		</view>
		<view class="user-private-tips">
			<uni-data-checkbox min="0" max="1" multiple v-model="agree" :localdata="[{value:0}]" @change="changeCheck">
			</uni-data-checkbox>
			<text style="color: black;">我已阅读且同意</text>
			<text @click="gotoPrivacyPolicy">《智能冰箱管家隐私保护指引》</text>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'

	export default {
		data() {
			return {
				formData: {
					avatarUrl: '',
					nickName: '',
					phone: '',
					code: ''
				},
				phone_len: 0,
				inputCode: false,
				_inputCode: true,
				seconds: 59,
				submiting: true,
				agree: [],

				rules: {
					nickName: {
						rules: [{
								required: true,
								errorMessage: '请输入昵称',
							},
							// 对name字段进行长度验证
							{
								minLength: 1,
								maxLength: 10,
								errorMessage: '长度在 {minLength} 到 {maxLength} 个字符',
							}
						],
						validateTrigger: 'submit'
					},
					phone: {
						// name 字段的校验规则
						rules: [
							// 对name字段进行长度验证
							{
								minLength: 11,
								maxLength: 11,
								errorMessage: '请输入正确的手机号',
							}
						],
						validateTrigger: 'submit'
					},
					code: {
						// name 字段的校验规则
						rules: [{
								required: true,
								errorMessage: '请输入验证码',
							},
							// 对name字段进行长度验证
							{
								minLength: 4,
								maxLength: 4,
								errorMessage: '长度在 {maxLength} 个字符',
							}
						],
						validateTrigger: 'submit'
					},
				}
			};
		},

		computed: {
			...mapState('user', ['token', 'userinfo'])
		},
		watch: {
			'formData.phone': {
				handler(newVal, oldVal) {
					this.phone_len = String(newVal).length
				}
			},
			agree: {
				handler(newVal, oldVal) {
					if (newVal[0] === 0)
						this.submiting = false
					else this.submiting = true
				}
			}
		},

		onLoad() {
			this.formData.avatarUrl = this.userinfo.avatarUrl || ''
			this.formData.nickName = this.userinfo.nickName || ''
			this.formData.phone = this.userinfo.phone || ''
		},

		onPullDownRefresh() {
			this.load()
			uni.stopPullDownRefresh()
		},

		methods: {
			load() {
				uni.$api.user.getUserInfo()
			},

			// 跳转
			gotoPrivacyPolicy() {
				uni.navigateTo({
					url: '/pagesSub/pageUser/user-privacy-policy/user-privacy-policy'
				})
			},

			// 请求
			async onChooseAvatar(e) {
				this.formData.avatarUrl = e.detail.avatarUrl
				uni.compressImage({
					src: e.detail.avatarUrl,
					success: (res) => {
						uni.uploadFile({
							url: uni.$uploadPath + '/upload/avatar',
							filePath: res.tempFilePath,
							name: 'avatar',
							header: {
								"token": this.token
							},
							formData: {},
							success: (res) => {
								if (res.statusCode !== 200)
									return uni.$showMsg('服务器繁忙')
								const {
									data: result
								} = JSON.parse(res.data)
								this.formData.avatarUrl = uni.$staticResourcePath +
									result
							},
							fail: (res) => {
								uni.$showMsg('服务器域名出错')
								console.log(res.errMsg);
							}
						});
					}
				})
			},
			async requestCode() {
				// 请求手机验证码
				const status = await uni.$api.user.getCellPhoneVerificationCode(this.formData.phone)
				if (status === 1) {
					this.seconds = 59
					this.inputCode = true
				}
			},
			updateUserInfo() {
				this.submiting = true
				if (this.formData.code == '') {
					this.formData.phone = this.userinfo.phone
				}
				setTimeout(() => {
					uni.$api.user.updateUserInfo(this.formData)
					this.submiting = false
					this.inputCode = false
				}, 1000)
			},

			// 事件处理
			inputnickName(e) {
				this.formData.nickName = e.detail.value
			},
			submit() {
				this.$refs.form.validate().then(res => {
					// console.log(JSON.stringify(this.formData));
					this.updateUserInfo()
				}).catch(err => {
					uni.$showMsg(err[0].errorMessage)
				})
			},
			timeup() {
				this.inputCode = false
			},
			changeCheck(e) {
				this.agree = [e.detail.value[0]]
			}
		}
	}
</script>

<style lang="scss">
	.container {
		height: 100vh;
		background-color: #fff;
	}

	.avatar-wrapper {
		padding: 0;
		width: 70px !important;
		border-radius: 8px;
		margin-top: 40px;
		margin-bottom: 40px;

		.avatar {
			display: block;
			width: 70px;
			height: 70px;
		}
	}

	.uni-forms {
		background-color: #fff;

		.uni-forms-item {
			padding: 8px 32px;
			margin-bottom: 0;
			// border-bottom: 1px solid #dddddd;

			.uni-forms-item__label {
				justify-content: center !important;
			}

			.uni-forms-item__content {
				display: flex;
			}
		}
	}

	.send-btn {
		display: flex;
		background-color: #94bfff;
		color: #fff;
		width: 20%;
		align-items: center;
		justify-content: center;
	}

	.countdown-box {
		background-color: #f1f1f1;
		display: flex;
		width: 20%;
		align-items: center;
		justify-content: center;
		color: #000;
	}

	.hover-send-btn {
		background-color: #f1f1f1;
	}

	.btn-submit {
		margin-top: 16px;
		padding: 0 32px;

		>button {
			background-color: #94bfff;
			color: #fff;
		}

	}

	.user-private-tips {
		margin-top: 16px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #3163c4;

		.uni-data-checklist .checklist-group .checklist-box {
			margin: 0 !important;
			margin-right: 0 !important;
		}
	}
</style>